/**
 * 数据库通信封装
 */

const mysql = require('mysql');
const mc = require('../config/mysql.js');

const pool = mysql.createPool(mc);

module.exports = async (sql, callback) => {
  await pool.getConnection((error, connection) => {
    if (error) {
      // 回调
      callback(true, { code: 1, msg: '数据库链接错误' });
      // 释放
      connection.release();
    } else {
      connection.query(sql, (err, data) => {
        if (err) {
          callback(true, { code: 1, msg: '服务错误' });
        } else {
          callback(false, { code: 0, data });
        }
        // 释放
        connection.release();
      });
    }
  });
};
